package com.oceanread.cn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oceanread.cn.config.MyConfig;
import com.oceanread.cn.config.Result;
import com.oceanread.cn.entity.Pipeline;

import com.oceanread.cn.entity.Query;
import com.oceanread.cn.service.IPipelineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/Pipeline")
@CrossOrigin()
@Api(value = "", tags = {"2.3-管线信息"})
public class PipelineController {

    @Autowired
    private IPipelineService iPipelineService;

    @GetMapping("/getall")
    public List<Pipeline> getAll() {
        return iPipelineService.getall();
    }

    @GetMapping("/findall")
    public JSONObject findall(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                              @RequestParam(name = "size", required = true, defaultValue = "10") int size) {
        JSONObject object = new JSONObject();
        object.put("data", iPipelineService.findall(page, size));
        object.put("total", iPipelineService.getnum());
        return object;
    }

    @PostMapping("/query")
    public List<Pipeline> query(@RequestBody Query query) {
        return iPipelineService.query(query.getKey(), query.getValue());
    }

    @GetMapping("/query1")
    public JSONObject query1(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                             @RequestParam(name = "size", required = true, defaultValue = "10") int size,
                             @RequestParam(name = "key") String key,
                             @RequestParam(name = "value") String value
    ) {
        JSONObject object = new JSONObject();
        object.put("data", iPipelineService.query1(key, value, page, size));
        object.put("total", iPipelineService.getnumquery(key, value));
        return object;
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody Pipeline pipeline) {
        try {
            iPipelineService.insert(pipeline.getPrjCode(), pipeline.getName(),
                    pipeline.getType(), pipeline.getIDLine(), pipeline.getIDPoint(),
                    pipeline.getNorth(), pipeline.getEast(), pipeline.getLat(),
                    pipeline.getLon(), pipeline.getDistance(), pipeline.getDisZ(),
                    pipeline.getAngle(), pipeline.getNote(), pipeline.getLine(),
                    pipeline.getPointOrder(), pipeline.getLength(), pipeline.getDepth());
            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }
    }

    @PostMapping("/update")
    public void update(@RequestBody Pipeline pipeline) {
        List<Pipeline> pipeline0 = iPipelineService.equal("SYSID", String.valueOf(pipeline.getSYSID()));
        pipeline0.get(0).setPointOrder(pipeline.getPointOrder());
        pipeline0.get(0).setLon(pipeline.getLon());
        pipeline0.get(0).setLat(pipeline.getLat());
        iPipelineService.update(pipeline0.get(0));
    }

    @ApiOperation(value = "更新管线线ID")
    @PostMapping("/updateIDLine")
    public Integer updateIDline(@RequestBody Pipeline pipeline) {
        System.out.println(pipeline);
        List<Pipeline> pipeline0 = iPipelineService.equal("SYSID", String.valueOf(pipeline.getSYSID()));
        List<Pipeline> pipelineList = iPipelineService.equal2("PrjCode", pipeline0.get(0).getPrjCode(), "IDLine", pipeline0.get(0).getIDLine());
        for (Pipeline pipeline1 : pipelineList) {
            pipeline1.setIDLine(pipeline.getIDLine());
            pipeline1.setType(pipeline.getType());
            pipeline1.setLength(pipeline.getLength());
            pipeline1.setDepth(pipeline.getDepth());
            iPipelineService.update(pipeline1);
        }
        return 1;
    }

    @ApiOperation(value = "删除管线节点")
    @GetMapping("/delete")
    public Integer delete(@RequestParam(name = "SYSID") int SYSID) {
        return iPipelineService.delete(SYSID);
    }

    @ApiOperation(value = "删除管线 线节点")
    @GetMapping("/deleteIDLine")
    public void deleteIDLine(@RequestParam(name = "SYSID") int SYSID) {
        List<Pipeline> pipeline0 = iPipelineService.equal("SYSID", String.valueOf(SYSID));
        List<Pipeline> pipelineList = iPipelineService.equal2("PrjCode", pipeline0.get(0).getPrjCode(), "IDLine", pipeline0.get(0).getIDLine());
        for (Pipeline pipeline1 : pipelineList) {
            iPipelineService.delete(pipeline1.getSYSID());
        }
    }

    @RequestMapping(value = "/uploadGeojson", method = RequestMethod.GET)
    @ResponseBody
    public Result uploadGeojson(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String filetype = fileName.substring(fileName.lastIndexOf("."));
        if (filetype.equals(".json"))//处理xls文件
        {
            try {
                String rootPath = MyConfig.getFilepath() + "json/Pipeline/";
                String storagePath = rootPath + file.getOriginalFilename();
                /*保存文件*/
                Streams.copy(file.getInputStream(), new FileOutputStream(storagePath), true);
                System.out.println(storagePath);
                return Result.success();
            } catch (IOException e) {
                return Result.error(e.getMessage());
            }
        }
        return Result.error();
    }

    @ApiIgnore(value = "废弃")
    @RequestMapping(value = "/getGeojsonfile/{JsonName}", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public byte[] getGeojsonfile(@PathVariable("JsonName") String JsonName) {
        try {
            System.out.println(JsonName);
            File file = new File(MyConfig.getFilepath() + "json/Pipeline/" + JsonName);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    @ApiOperation(value = "前端获取GeoJson")
    @RequestMapping(value = "/getGeojson/{prjCode}", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getGeojson(@PathVariable("prjCode") String prjCode) {
        try {
            JSONArray features = new JSONArray();
            List<Pipeline> pipelines = iPipelineService.getLine(prjCode);
            for (Pipeline pipeline : pipelines) {
                JSONObject feature = new JSONObject();
                feature.put("type", "Feature");

                JSONObject properties = new JSONObject();
                properties.put("PrjCode", pipeline.getPrjCode());
                properties.put("Name", pipeline.getName());
                properties.put("Type", pipeline.getType());
                properties.put("IDLine", pipeline.getIDLine());
                properties.put("length", pipeline.getLength());
                properties.put("depth", pipeline.getDepth());
                feature.put("properties", properties);

                System.out.println(pipeline.getIDLine());
                List<Pipeline> points = iPipelineService.getPoint(prjCode, pipeline.getIDLine());

                JSONObject geometry = new JSONObject();
                geometry.put("type", "LineString");
                ArrayList<float[]> coordinates = new ArrayList<float[]>();
                for (Pipeline point : points) {
                    float[] lonlat = new float[2];
                    lonlat[0] = Float.parseFloat(point.getLon());
                    lonlat[1] = Float.parseFloat(point.getLat());
                    coordinates.add(lonlat);
                }
                geometry.put("coordinates", coordinates);
                feature.put("geometry", geometry);
                features.add(feature);
            }

            JSONObject geojson = new JSONObject();
            geojson.put("type", "FeatureCollection");
            geojson.put("features", features);
            return geojson;
        } catch (Exception e) {
            JSONObject object = new JSONObject();
            object.put("error", e.getMessage());
            return object;
        }
    }

    @ApiOperation(value = "后台获取管线信息")
    @RequestMapping(value = "/getinfo/{prjCode}", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getinfo(@PathVariable("prjCode") String prjCode,
                              @RequestParam(name = "page", required = true, defaultValue = "1") int page,
                              @RequestParam(name = "size", required = true, defaultValue = "10") int size) {
        try {
            JSONObject result = new JSONObject();
            JSONArray infos = new JSONArray();
            List<Pipeline> pipelines = iPipelineService.getLine_Page(prjCode, page, size);
            for (Pipeline pipeline : pipelines) {
                JSONObject info = new JSONObject();
                info.put("SYSID", pipeline.getSYSID());
                info.put("PrjCode", pipeline.getPrjCode());
                info.put("Name", pipeline.getName());
                info.put("Type", pipeline.getType());
                info.put("IDLine", pipeline.getIDLine());
                info.put("length", pipeline.getLength());
                info.put("depth", pipeline.getDepth());
                infos.add(info);
            }
            Integer total = iPipelineService.getLine_Num(prjCode);
            result.put("data", infos);
            result.put("total", total);
            return result;
        } catch (Exception e) {
            JSONObject object = new JSONObject();
            object.put("error", e.getMessage());
            return object;
        }
    }

    @ApiOperation(value = "后台获取管线节点")
    @RequestMapping(value = "/getnotes/{prjCode}/{IDLine}", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getnotes(@PathVariable("prjCode") String prjCode, @PathVariable("IDLine") String IDLine,
                               @RequestParam(name = "page", required = true, defaultValue = "1") int page,
                               @RequestParam(name = "size", required = true, defaultValue = "10") int size) {
        try {
            JSONObject result = new JSONObject();
            JSONArray notes = new JSONArray();
            List<Pipeline> pipelines = iPipelineService.getPoint_Page(prjCode, IDLine, page, size);
            for (Pipeline pipeline : pipelines) {
                JSONObject info = new JSONObject();
                info.put("SYSID", pipeline.getSYSID());
                info.put("PrjCode", pipeline.getPrjCode());
                info.put("Name", pipeline.getName());
                info.put("IDLine", pipeline.getIDLine());
                info.put("Lon", pipeline.getLon());
                info.put("Lat", pipeline.getLat());
                info.put("Type", pipeline.getType());
                info.put("pointOrder", pipeline.getPointOrder());
                notes.add(info);
            }
            Integer total = iPipelineService.getPoint_Num(prjCode, IDLine);
            result.put("data", notes);
            result.put("total", total);
            return result;
        } catch (Exception e) {
            JSONObject error = new JSONObject();
            error.put("error", e.getMessage());
            return error;
        }
    }

    @ApiOperation(value = "Pipeline统一插入")
    @RequestMapping(value = "/PipelineInsert", method = RequestMethod.POST)
    public void inserttest(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader reader = request.getReader();
            if (reader != null) {
                String redaline = reader.readLine();
                JSONObject readobject = JSONObject.parseObject(redaline);
                JSONObject data = readobject.getJSONObject("data");
                System.out.println(data);
                String PrjCode = data.getString("PrjCode");
                String Name = data.getString("Name");

                String IDLine = data.getString("IDLine");
                String Type = data.getString("Type");
                String length = data.getString("length");
                String depth = data.getString("depth");

                JSONArray pipelineInformationData = data.getJSONArray("pipelineInformationData");
                ArrayList<Pipeline> pipelineArrayList = new ArrayList<Pipeline>();
                if (pipelineInformationData.size() > 0) {
                    for (int i = 0; i < pipelineInformationData.size(); i++) {
                        Pipeline pipeline = new Pipeline();
                        pipeline.setPrjCode(PrjCode);
                        pipeline.setName(Name);
                        pipeline.setIDLine(IDLine);
                        pipeline.setType(Type);
                        pipeline.setLength(length);
                        pipeline.setDepth(depth);
                        String pointOrder = pipelineInformationData.getJSONObject(i).getString("pointOrder");
                        pipeline.setPointOrder(Integer.valueOf(pointOrder));
                        pipeline.setLon(pipelineInformationData.getJSONObject(i).getString("Lon"));
                        pipeline.setLat(pipelineInformationData.getJSONObject(i).getString("Lat"));
                        pipelineArrayList.add(pipeline);
                    }
                    if (IDLine != "" && IDLine != null) {
                        for (Pipeline pipeline : pipelineArrayList) {//循环插入
                            iPipelineService.insert(pipeline.getPrjCode(), pipeline.getName(),
                                    pipeline.getType(), pipeline.getIDLine(), pipeline.getIDPoint(),
                                    pipeline.getNorth(), pipeline.getEast(), pipeline.getLat(),
                                    pipeline.getLon(), pipeline.getDistance(), pipeline.getDisZ(),
                                    pipeline.getAngle(), pipeline.getNote(), pipeline.getLine(),
                                    pipeline.getPointOrder(), pipeline.getLength(), pipeline.getDepth());
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}
